(function () {

	// insértion dynamique de la feuille de style
    var headID = document.getElementsByTagName("head")[0];
    var cssNode = document.createElement('link');
    cssNode.type = 'text/css';
    cssNode.rel = 'stylesheet';
    cssNode.href = 'http://ftvi.googlecode.com/git/budget/budget.css';
    headID.appendChild(cssNode);

var budgetArray = [
    {
        mission: "Enseignement scolaire",
        colorCode: "FF7505",
        subCatColorCode: "fcd5b4",
        2011: {budget: "61796818861"}, 
        2012: {budget: "62330708743"},
        2013: {budget: "64010000000"},
        sub_categories: [
            {mission: "Enseignement public",
            	colorCode: "FF8B32",
                2011: {budget: "47476016991", percentage: "76.83"}, 
                2012: {budget: "47830080084", percentage: "76.74"},
                2013: {budget: "49265000000"}
            },
            {mission: "Enseignement privé",
            	colorCode: "FFA968",
                2011: {budget: "7082403910", percentage: "11.46"}, 
                2012: {budget: "7105604620", percentage: "11.40"},
                2013: {budget: "7081000000"}
            },
            {mission: "Autres",
            	colorCode: "FFC093",
                2011: {budget: "7238397960", percentage: "11.71"}, 
                2012: {budget: "7395024039", percentage: "11.86"},
                2013: {budget: "7664000000"}
            }    
        ]
    },
    
    {
        mission: "Charge de la dette",
        colorCode: "00547F",
        subCatColorCode: "fcd5b4",
        2011: {budget: "46926813783"}, 
        2012: {budget: "49921176591"},
        2013: {budget: "46895000000"}
    },
    
   
    {
        mission: "Défense",
        colorCode: "E6F700",
        subCatColorCode: "eaf1dd",
        2011: {budget: "37420581958"}, 
        2012: {budget: "38281251488"},
        2013: {budget: "38200000000"}
    },
    
    {
        mission: "Recherche et enseignement supérieur",
        colorCode: "FF0000",
        subCatColorCode: "dbe5f1",
        2011: {budget: "25194200112"}, 
        2012: {budget: "25439452934"},
        2013: {budget: "25956000000"},
        sub_categories: [
            {mission: "Enseignement supérieur",
            	colorCode: "FF2828",
                2011: {budget: "12270039804", percentage: "48.70"}, 
                2012: {budget: "12510395732", percentage: "49.18"},
                2013: {budget: "12760000000"}
            },
            {mission: "Recherche",
            	colorCode: "FF5B5B",
                2011: {budget: "10540121534", percentage: "41.84"}, 
                2012: {budget: "10453255638", percentage: "41.09"},
                2013: {budget: "10562000000"}
            },
            {mission: "Vie étudiante",
            	colorCode: "FF8787",
                2011: {budget: "2083895502", percentage: "8.27"}, 
                2012: {budget: "2168571845", percentage: "8.52"},
                2013: {budget: "2325000000"}
            },
            {mission: "Autres",
            	colorCode: "FFC1C1",
                2011: {budget: "300143272", percentage: "1.19"}, 
                2012: {budget: "307229719", percentage: "1.21"},
                2013: {budget: "309000000"}
            }
        ]
    },
    
     {
        mission: "Sécurité",
        colorCode: "0B4700",
        subCatColorCode: "f2dddc",
        2011: {budget: "16819486999"}, 
        2012: {budget: "17063306021"},
        2013: {budget: "17417000000"},
        sub_categories: [
            {mission: "Police nationale",
            	colorCode: "4B8E44",
                2011: {budget: "9088266756", percentage: "54.03"}, 
                2012: {budget: "9210360780", percentage: "53.98"},
                2013: {budget: "9476000000"}
            },
             {mission: "Gendarmerie nationale",
            	colorCode: "678C63",
                2011: {budget: "7731220243", percentage: "45.97"}, 
                2012: {budget: "7852945241", percentage: "46.02"},
                2013: {budget: "7941000000"}
            }
        ]
    },
    
    {
        mission: "Solidarité et égalité des chances",
        colorCode: "410077",
        subCatColorCode: "e5e0ec",
        2011: {budget: "12366477409"}, 
        2012: {budget: "12753746545"},
        2013: {budget: "13400000000"},
        sub_categories: [
            {mission: "Handicap et dépendance",
            	colorCode: "4F2475",
                2011: {budget: "9883734198", percentage: "79.92"}, 
                2012: {budget: "10481634198", percentage: "82.18"},
                2013: {budget: "11168000000"}
            },
             {mission: "Lutte contre la pauvreté (RSA)",
            	colorCode: "593F72",
                2011: {budget: "705000000", percentage: "5.70"}, 
                2012: {budget: "535000000", percentage: "4.19"},
                2013: {budget: "404000000"}
            },
            {mission: "Autres",
            	colorCode: "5D4A70",
                2011: {budget: "1777743211", percentage: "14.38"}, 
                2012: {budget: "1737112347", percentage: "13.62"},
                2013: {budget: "1828000000"}
            }
        ]
    },
    
    {
        mission: "Travail et emploi",
        colorCode: "009DFF",
        subCatColorCode: "c5d9f1",
        2011: {budget: "11463085448"}, 
        2012: {budget: "10187677822"},
        2013: {budget: "10316000000"},
        sub_categories: [
            {mission: "Pôle Emploi et contrats aidés",
            	colorCode: "6BC6FF",
                2011: {budget: "6193152552", percentage: "54.03"}, 
                2012: {budget: "5367996853", percentage: "52.69"},
                2013: {budget: "5704000000"}
            },
             {mission: "Formation et chômage partiel",
            	colorCode: "91D4FF",
                2011: {budget: "4448274090", percentage: "38.81"}, 
                2012: {budget: "3995409510", percentage: "39.22"},
                2013: {budget: "3750000000"}
            },
            {mission: "Autres",
            	colorCode: "B7E3FF",
                2011: {budget: "821658806", percentage: "7.17"}, 
                2012: {budget: "824271459", percentage: "8.09"},
                2013: {budget: "862000000"}
            }
        ]
    },
    
    {
        mission: "Écologie et développement durable",
        colorCode: "FCB000",
        subCatColorCode: "fde9d9",
        2011: {budget: "9532597507"}, 
        2012: {budget: "9742828295"},
        2013: {budget: "8380000000"}
    },
    
    {
        mission: "Ville et logement",
        colorCode: "D7E200",
        subCatColorCode: "eaf1dd",
        2011: {budget: "7606994582"}, 
        2012: {budget: "7721115678"},
        2013: {budget: "8000000000"},
        sub_categories: [
            {mission: "Aide à l'accès au logement",
            	colorCode: "DBE05C",
                2011: {budget: "5285354585", percentage: "69.48"}, 
                2012: {budget: "5603134727", percentage: "72.57"},
                2013: {budget: "4893000000"}
            },
             {mission: "Autres",
            	colorCode: "DADD7C",
                2011: {budget: "2321639997", percentage: "30.52"}, 
                2012: {budget: "2117980951", percentage: "27.43"},
                2013: {budget: "3107000000"}
            }
        ]
    },
    
    {
        mission: "Justice",
        colorCode: "0089F2",
        subCatColorCode: "ffffcc",
        2011: {budget: "7127986406"}, 
        2012: {budget: "7420577901"},
        2013: {budget: "7746000000"},
        sub_categories: [
            {mission: "Tribunaux",
            	colorCode: "58AEEF",
                2011: {budget: "2959680413", percentage: "41.52"}, 
                2012: {budget: "2978583537", percentage: "40.14"},
                2013: {budget: "3100000000"}
            },
             {mission: "Prison",
            	colorCode: "93C7ED",
                2011: {budget: "2811928579", percentage: "39.45"}, 
                2012: {budget: "3030315325", percentage: "40.84"},
                2013: {budget: "3200000000"}
            },
            {mission: "Autres",
            	colorCode: "AFD2EA",
                2011: {budget: "1356377414", percentage: "19.03"}, 
                2012: {budget: "1411679039", percentage: "19.02"},
                2013: {budget: "1446000000"}
            }
        ]
    },
    
    {
        mission: "Agriculture",
        colorCode: "323844",
        subCatColorCode: "f2f2f2",
        2011: {budget: "3674050948"}, 
        2012: {budget: "3598417028"},
        2013: {budget: "3360000000"}
    },
    
    {
        mission: "Culture",
        colorCode: "B50048",
        subCatColorCode: "f2dddc",
        2011: {budget: "2672811450"}, 
        2012: {budget: "2732298491"},
        2013: {budget: "2630000000"}
    },
    
    {
        mission: "Pouvoirs publics",
        asterisk : "* ",
        asteriskText : "Elysée, Assemblée nationale, Sénat...",
        colorCode: "B50048",
        subCatColorCode: "f2dddc",
        2011: {budget: "1017915150"}, 
        2012: {budget: "1026092564"},
        2013: {budget: "990000000"}
    },
    {
        mission: "Autres",
        asterisk : "** ",
        asteriskText : "Diplomatie, outre-mer, immigration, aides aux médias, tourisme, sécurité civile, aide publique au développement, anciens combattants...",
        colorCode: "4F1E00",
        subCatColorCode: "f2dddc",
        2011: {budget: "45458305951"}, 
        2012: {budget: "46256357537"},
        2013: {budget: "45920000000"}
    }
];

// variables pour les données à passer à HighCharts
var HCcats = [],
	HCsubcats = [];

// montant du budget maximum à comparer
var totalBudget = 75000000000;
// largeur barre
var barWidth = 800;
// Html du graph
var barHtml = '';
//Html de la legende du graph HighChart
var chartLegendHtml = '<div id="chartLegend">';

// premier boucle pour les categories de premier niveau

$.each(budgetArray, function (index, value) {
	
	var firstSegmentWidth = ((barWidth * value[2013].budget) / totalBudget); // année 2013
	var secondSegmentWidth = ((barWidth * value[2012].budget) / totalBudget); // année 2012
	var thirdSegmentWidth = ((barWidth * value[2011].budget) / totalBudget); // année 2011
	var thisFirstLevelFirstBudget = (Number(value[2013].budget) / 100000000000) * 100 // année 2013;
	var thisFirstLevelSecondBudget = (Number(value[2012].budget) / 100000000000) * 100 // année 2012;
	var thisFirstLevelThirdBudget = (Number(value[2011].budget) / 100000000000) * 100 // année 2011;
	var augmented = '';
	
	// prépares l'html pour la legende de HighChart
	chartLegendHtml += '<div class="hcLegend"><div style="background-color: #' + value.colorCode + '"></div><p style="color: #' + value.colorCode + '">' + value.mission + '</p></div>';
	
	// prepare les données pour HighCharts pour l'année la plus recente (categories de premier niveau)
	HCcats.push({
			name: value.mission,
			color: '#' + value.colorCode,
			y: Number(thisFirstLevelFirstBudget.toFixed(2)),
			id: value[2013].budget,
			events: {
            	click: function (e) {
            		location = '#' + this.id;	
            	}
            }
		});
	
	if (Number(value[2013].budget) > Number(value[2012].budget)) {
		augmented = 'augmented';
	} else if (Number(value[2013].budget) == Number(value[2012].budget)) {
		augmented = 'egual';
	} else {
		augmented = 'notAugmented';
	}
	
	barHtml += '<a name="' + value[2013].budget + '"></a> <div class="category">';
	
	// ajoute une couleur de fond pour la barre de priemer niveau seulement si cette categorie n'a pas des sous categories (ça resou un petit souci d'un pixel de trop)
	var barColor = '';
	
	if (!value.sub_categories) {
		barColor = 'background-color: #'+ value.colorCode;
	}
	
	// titre categorie de premier niveau et premiere barre pour l'année 2013
	var asterisk = '',
	 asteriskText = '';
	if (value.asterisk) {
		asteriskText = '<h4 class="asterisk">' + '<span>' + value.asterisk + '</span>' + value.asteriskText +'</h4>';
		asterisk = '<span>' + value.asterisk + '</span>';
		
	}
	
	barHtml += '<h2 class="'+ augmented + '">'+ value.mission + asterisk +'</h2><div class="yearGroup"><h3>2013</h3><div style="width: ' + (Number(firstSegmentWidth.toFixed()) + 1)  +  'px;'+  barColor +'" class="bar">';
	
	var borderClass = "";
	var barWidthSubCat;
	var firstSegmentWidthSubCat;
	
	if (value.sub_categories) {
		
		var subCatsNumber = value.sub_categories.length;
		
		// deuxieme boucle pour les sous categories de deuxieme niveau pour l'année 2013
		
		$.each(value.sub_categories, function (secondIndex, secondValue) {
				
			if ((secondIndex) + 1 == subCatsNumber) {
				borderClass = "lastSubCat";
			}
			barWidthSubCat = firstSegmentWidth;
			firstSegmentWidthSubCat = ((barWidthSubCat * secondValue[2013].budget) / value[2013].budget); // année 2013
			barHtml += '<div style="width: ' + firstSegmentWidthSubCat.toFixed()  +  'px; background-color: #'+ secondValue.colorCode  +'" class="secondLevelBar '+ borderClass +'">';
			var thisSecondLevelBudget = (Number(secondValue[2013].budget) / 100000000000) * 100;
			
			
			// prepare les données pour HighCharts pour l'année la plus recente (sous categories)
			HCsubcats.push({
					name: secondValue.mission,
					color: '#' + value.colorCode,
					y: Number(thisSecondLevelBudget.toFixed(2)),
					id: value[2013].budget,
					events: {
		            	click: function (e) {
		            		console.log(this);
		            		location = '#' + this.id;	
		            	}
		            }
			});
			
			barHtml += '<div style="border: 1px solid #'+ value.colorCode +'" class="secondLevelBarPopUp"><p>'+ secondValue.mission +'</p><p class="budgetMoney">'+thisSecondLevelBudget.toFixed(2) + ' Md€</p></div>';
			barHtml += '</div>';
			
		});
		
	} else {
		
		// prepare les données pour HighCharts pour l'année la plus recente (sous categories quand il n'y a pas de sous categories)
		HCsubcats.push({
				name: value.mission,
				color: '#' + value.colorCode ,
				y: Number(thisFirstLevelFirstBudget.toFixed(2)),
				id: value[2013].budget,
				events: {
	            	click: function (e) {
	            		console.log(this);
	            		location = '#' + this.id;	
	            	}
	            }
		});
	}
	
	barHtml +='</div><h3 class="budget">'+ thisFirstLevelFirstBudget.toFixed(2) +' Md€</h3></div>';
	
	// deuxieme barre pour l'année 2012
	
	barHtml += '<div class="clearboth yearGroup"><h3>2012</h3><div style="width: ' + (Number(secondSegmentWidth.toFixed()) + 1 )  +  'px;' + barColor + '" class="bar">';
	
	if (value.sub_categories) {
		
		// troisieme boucle pour les sous categories de deuxieme niveau pour l'année 2012
		
		$.each(value.sub_categories, function (thirdIndex, thirdValue) {
			
			borderClass = "";
			if ((thirdIndex) + 1 == subCatsNumber) {
				borderClass = "lastSubCat";
			}
			barWidthSubCat = secondSegmentWidth;
			firstSegmentWidthSubCat = ((barWidthSubCat * thirdValue[2012].budget) / value[2012].budget); // année 2012
			barHtml += '<div style="width: ' + firstSegmentWidthSubCat.toFixed()  +  'px; background-color: #'+ thirdValue.colorCode  +'" class="secondLevelBar '+ borderClass +'">';
			thisSecondLevelBudget = (Number(thirdValue[2012].budget) / 100000000000) * 100;
			barHtml += '<div style="border: 1px solid #'+ value.colorCode +'" class="secondLevelBarPopUp"><p>'+ thirdValue.mission +'</p><p class="budgetMoney">'+thisSecondLevelBudget.toFixed(2) + ' Md€</p></div>';
			barHtml += '</div>';
			
		});
	}

	
	barHtml += '</div><h3  class="budget">'+ thisFirstLevelSecondBudget.toFixed(2) +' Md€</h3></div>';
	
	// troisieme barre pour l'année 2011
	
	barHtml += '<div class="clearboth yearGroup"><h3>2011</h3><div style="width: ' + (Number(thirdSegmentWidth.toFixed()) + 1 )  +  'px;' + barColor + '" class="bar">';
	
	if (value.sub_categories) {
		
		// qatrieme boucle pour les sous categories de deuxieme niveau pour l'année 2011
		
		$.each(value.sub_categories, function (fourthIndex, fourthValue) {
			
			borderClass = "";
			if ((fourthIndex) + 1 == subCatsNumber) {
				borderClass = "lastSubCat";
			}
			barWidthSubCat = thirdSegmentWidth;
			firstSegmentWidthSubCat = ((barWidthSubCat * fourthValue[2011].budget) / value[2011].budget); // année 2011
			barHtml += '<div style="width: ' + firstSegmentWidthSubCat.toFixed()  +  'px; background-color: #'+ fourthValue.colorCode  +'" class="secondLevelBar '+ borderClass +'">';
			thisSecondLevelBudget = (Number(fourthValue[2011].budget) / 100000000000) * 100;
			barHtml += '<div style="border: 1px solid #'+ value.colorCode +'" class="secondLevelBarPopUp"><p>'+ fourthValue.mission +'</p><p class="budgetMoney">'+thisSecondLevelBudget.toFixed(2) + ' Md€</p></div>';
			barHtml += '</div>';
			
		});
	}

	
	barHtml += '</div><h3  class="budget">'+ thisFirstLevelThirdBudget.toFixed(2) +' Md€</h3></div>';
	
	
	
	barHtml += asteriskText + '</div>';
	
});

chartLegendHtml += '</div>';

$(document).ready(function() {
	
	// HighCharts
	chart = new Highcharts.Chart({
        chart: {
            renderTo: 'budgetChart', /* ajoutes le graph HighCharts à la page  */
            type: 'pie'
        },
        plotOptions: {
        	series: {
                cursor: 'pointer',
                dataLabels: {
                    style: {
                    	fontFamily: 'Verdana, Arial, Helvetica, sans-serif', // default font
                    	fontSize: '12px',
                        fontWeight:'normal'
                    }
                }
            },
            pie: {
                shadow: false
            }
        },
        credits: {enabled: false},
        title: {
            text: ''
        },
        yAxis: {
            title: {
                text: 'Budget'
            }
        },
        tooltip: {
            valueSuffix: 'Md€'
        },
        series: [{
            name: 'Budget',
            data: HCcats,
            size: '60%',
            dataLabels: {
            	formatter: function() {
                    // display only if larger than 1
                    return this.y > 1 ? '<b>'+ this.point.name +':</b> '+ this.y +'Md€'  : null;
                }
            }
        }]
    });
    
	// ajoutes l'html des graphs
	$('#budgetGraph').html(barHtml);
	
	// ajoute la legende du graph 
	$('#budgetGraph').append('<h3 class="smallLegends">Sources : <a href="http://www.assemblee-nationale.fr/13/projets/pl2824.asp">PLF 2011</a>, <a href="http://www.assemblee-nationale.fr/13/projets/pl3775.asp">PLF 2012</a>, <a href="http://www.economie.gouv.fr/projet-loi-finances-pour-2013-projet-loi-programmation-finances-publiques-2012-2017">PLF 2013</a></h3>');
	
	// ajoute la legende du graph Highcharts
	$('#budgetChart').append('<h3 class="smallLegends">Source : <a href="http://www.economie.gouv.fr/projet-loi-finances-pour-2013-projet-loi-programmation-finances-publiques-2012-2017"> PLF 2013</a></h3>');
	
	/* // ajoutes la legende du graph HighChart en dessous du graph HighChart
	$('#budgetChart').append(chartLegendHtml); */
	
	// popup dans les carrés des deuxieme niveaux dans les graphs
	$('.secondLevelBar').hover(function() {
		$(this).children('.secondLevelBarPopUp').show();
	}, function () {
		$(this).children('.secondLevelBarPopUp').hide();
	});
	
});

})();








